import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { StringCodecManager } from '../string_manager/StringCodecManager';

/**
 * md5 和 sha256 算法默认返回小写字符串,需要大写自己进行转换.
 */
export class CryptoManager {
  static async md5U8a(u8a: Uint8Array): Promise<Uint8Array> {
    let md = cryptoFramework.createMd("MD5");
    await md.update({ data: u8a });
    let outputBlob: cryptoFramework.DataBlob = await md.digest();
    return outputBlob.data;
  }

  static async sha256U8a(u8a: Uint8Array): Promise<Uint8Array> {
    return CryptoManager.cryptoU8a(u8a, "SHA256");
  }

  static async cryptoU8a(u8a: Uint8Array, mdName: string = "MD5"): Promise<Uint8Array> {
    let md = cryptoFramework.createMd(mdName);
    await md.update({ data: u8a });
    let outputBlob: cryptoFramework.DataBlob = await md.digest();
    return outputBlob.data;
  }


  static async md5String(str: string): Promise<string> {
    let u8a = StringCodecManager.stringToU8aWithUtf8(str);
    let outputU8a = await CryptoManager.md5U8a(u8a)
    let string = StringCodecManager.u8aToString_valueDisplay(outputU8a, 16)
    return string;
  }

  static async sha256String(str: string): Promise<string> {
    return CryptoManager.cryptoString(str, "SHA256");
  }

  static async cryptoString(str: string, mdName: string = "MD5"): Promise<string> {
    let u8a = StringCodecManager.stringToU8aWithUtf8(str);
    let outputU8a = await CryptoManager.cryptoU8a(u8a)
    let string = StringCodecManager.u8aToString_valueDisplay(outputU8a, 16)
    return string;
  }
}